﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P46011Controller : ControllerBase
    {


        [HttpPost]
        public ActionResult<MQResponse> Query(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            P46011param param = Common.JsonHelper.JsonToObject<P46011param>(((Newtonsoft.Json.Linq.JObject)objpram).ToString());

            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new MQException("401", "请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);
                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine( $"查询{param.itemnumber}包装信息");

                FormActionsCollection fs = new FormActionsCollection();
                fs.Add(new FSREvent() { controlID="21", command = "SetControlValue",value=param.itemnumber });
                fs.Add(new FSREvent() { controlID = "1[26]", command = "SetQBEValue", value = param.UOM });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "15" });

                FormRequest request = new FormRequest()
                {
                    formName = "P46011_W46011A",
                    version = "MCL002",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P46011_W46011A"))
                {
                    JObject obj = response.ToJObject();
                    int  rowcount = Convert.ToInt32(obj["fs_P46011_W46011A"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"{param.itemnumber}查询到记录:{rowcount} 条");
                    //应该查询到数据
                    if (rowcount > 0)
                    {
                        JObject objRow = JObject.Parse( obj["fs_P46011_W46011A"]["data"]["gridData"]["rowset"][0].ToString());
                        execresult.Result = JsonHelper.ObjectToJson(new P46011param() {
                             itemnumber=param.itemnumber,
                             UOM=param.UOM,
                             L=Convert.ToDecimal(objRow["z_GDEP_33"]["value"].ToString()),
                             W = Convert.ToDecimal(objRow["z_GWID_32"]["value"].ToString()),
                             H = Convert.ToDecimal(objRow["z_GHET_34"]["value"].ToString()),
                             packingvolume= Convert.ToDecimal(objRow["z_GCUB_37"]["value"].ToString()), 
                             grossWeight =  Convert.ToDecimal(objRow["z_GWEI_39"]["value"].ToString())
                        });
                        //execresult.Message = response.JsonString;
                    }
                }
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            return execresult;
        }
    }
}